<!DOCTYPE html>
<html>
<title>Login Page :: DIF233 - Unit 1 - Excercise 2</title>
<body>
	<?php
		function get_connection(){
			$file = fopen("config.txt","r+") or exit("Sorry not able to open the register file");
			$line = fgets($file);
			$value = explode(":", $line);
			$connection = mysqli_connect($value[0], $value[1], $value[2], $value[3]);
				
			if(mysqli_connect_errno($connection)){
				echo "unable to connect to test data base";
				exit("unable to connect to test data base");
			}else{
				return $connection;
			}
		}
		function valid_user($connection,$user,$passwd){
			$get_user_details = "select id from user_credentials where user_name = '".$user."'"." and password='".$passwd."'";
			$result = mysqli_query($connection, $get_user_details);
			$count = 0;
			while($row = mysqli_fetch_array($result)){
				$count = $row["id"];
			}
			return $count;
		}
		if(!empty($_POST["submit"])){
			$connection = get_connection();
			if($count = valid_user($connection,$_POST["user_id"], $_POST["password"])){
				header("Location: user.php?id=".$count);
				exit();
			}else{
				echo "<h3>Bad Credentials</h3>";
			}
			mysqli_close($connection);
		}	
	?>
<form name="login" action="login.php" method="post">
		<table border="0" width="100%">
		<tr>
			<td>
				User Name:
			</td>
			<td>
				<input type="text" name="user_id" required/>
			</td>
		</tr>
		<tr>
			<td>
				Password:
			</td>
			<td>
				<input type="password" name="password" required/>
			</td>
		</tr>		
		<tr>
			<td colspan="2"><input type="submit" name="submit" value="submit"/></td>
		</tr>		
	</table>
</form>
</body>
</html>
